<template>
  <el-card class="details">
    <el-tabs>
      <el-tab-pane label="登录账户设置">
        <el-form ref="form" label-width="80px" :model="form" :rules="rules">
          <el-form-item label="姓名：" prop="username">
            <el-input v-model="form.username" />
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input v-model="form.password" type="password" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="update">更新</el-button>
            <el-button @click="$router.push('/employees')">取消</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="个人详情" lazy>
        <component
          :is="'UserInfo'"
          :user-info="initUserInfo"
          @updateUserInfo="updateUserInfo"
        />
      </el-tab-pane>
      <el-tab-pane label="岗位信息" lazy>
        <component :is="'JobInfo'" />
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script>
import { sysUser } from '@/api/user.js'
import { sysUserPut } from '@/api/employees.js'
export default {
  name: 'Details',
  components: {
    UserInfo: () => import('./components/user-info.vue'),
    JobInfo: () => import('./components/job-info.vue')
  },
  data() {
    return {
      id: this.$route.params.id,
      userInfo: '',
      initUserInfo: {},
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '必填', trigger: 'blur' }],
        password: [{ required: true, message: '必填', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    // 获取员工信息
    async getUserInfo() {
      const res = await sysUser(this.id)
      res.data.formOfEmployment = res.data.formOfEmployment || 1
      this.userInfo = res.data
      this.initUserInfo = JSON.parse(JSON.stringify(res.data))
      this.form.username = res.data.username
    },
    // 更新按钮点击
    update() {
      this.$refs.form.validate(async(result) => {
        if (result) {
          await sysUserPut({ ...this.userInfo, ...this.form })
          this.$message.success('更新成功')
          this.initUserInfo.username = this.form.username
        }
      })
    },
    // 个人详情修改同步到登录账户设置页面
    updateUserInfo() {
      this.userInfo = JSON.parse(JSON.stringify(this.initUserInfo))
      this.form.username = this.userInfo.username
    }
  }
}
</script>

<style lang="scss" scoped>
.details {
  margin: 20px;
  .el-form {
    margin: 30px 0 0 300px;
    .el-input {
      width: 300px;
    }
  }
}
</style>
